package com.feng.utils;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author xiaofeng
 * @date 2021/06/19
 * @desc
 **/
public class DBConnectionManager {
    private static final String COMPONENT_ENV_CONTEXT_NAME = "java:comp/env";

    public static Connection getConnection() {
        DataSource dataSource;
        try {
            Context context = new InitialContext();
            Context envContext = (Context) context.lookup(COMPONENT_ENV_CONTEXT_NAME);
            dataSource = (DataSource) envContext.lookup("jdbc/UserPlatformDataSource");
        } catch (NamingException e) {
            throw new RuntimeException(e);
        }

        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            System.out.println("获取 JNDI 数据库连接异常！" + e.getMessage());
        }
        if (connection != null) {
            System.out.println("获取 JNDI 数据库连接成功！");
        }
        return connection;
    }

}
